﻿
//为⾼尔夫⽐赛砍树
class Solution {
    int m, n;
public:
    int cutOffTree(vector<vector<int>>& f) {
        m = f.size(), n = f[0].size();
        vector<pair<int, int>> trees;
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (f[i][j] > 1) trees.push_back({ i, j });
        sort(trees.begin(), trees.end(), [&](const pair<int, int>& p1, const pair<int, int>& p2)
            {
                return f[p1.first][p1.second] < f[p2.first][p2.second];
            });

        int ret = 0;
        int bx = 0, by = 0;
        for (auto& [a, b] : trees)
        {
            int step = bfs(f, bx, by, a, b);
            if (step == -1) return -1;
            ret += step;
            bx = a;
            by = b;
        }
        return ret;
    }

    int dx[4] = { 0, 0, 1, -1 };
    int dy[4] = { 1, -1, 0 ,0 };
    bool vis[51][51];

    int bfs(vector<vector<int>>& f, int i, int j, int bx, int by)
    {
        if (i == bx && j == by) return 0;
        queue<pair<int, int>> q;
        memset(vis, 0, sizeof vis);
        q.push({ i, j });
        vis[i][j] = true;
        int ret = 0;
        while (q.size())
        {
            ++ret;
            int sz = q.size();
            while (sz--)
            {
                auto [a, b] = q.front();
                q.pop();
                for (int k = 0; k < 4; k++)
                {
                    int x = a + dx[k], y = b + dy[k];
                    if (x >= 0 && x < m && y >= 0 && y < n && f[x][y] != 0 && !vis[x][y])
                    {
                        if (x == bx && y == by) return ret;
                        vis[x][y] = true;
                        q.push({ x, y });
                    }
                }
            }
        }
        return -1;
    }
};


//反转字符串
class Solution {
public:
    void reverseString(vector<char>& s) {
        int left = 0, right = s.size() - 1;
        while (left < right)
        {
            swap(s[left++], s[right--]);
        }
    }
};

//寻找重复数
class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        int min = 1, max = nums.size() - 1;
        while (min < max)
        {
            int mid = min + (max - min) / 2, count = 0;
            for (auto x : nums)
                if (x >= min && x <= mid)
                    ++count;
            if (count > mid - min + 1)
                max = mid;
            else
                min = mid + 1;
        }
        return min;
    }
};